package com.mix;

import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
// 参考：https://blog.51cto.com/u_16213590/11694939
public class ExcelWatermarkUtil {

    public static void main(String[] args) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\zhoubin\\Desktop\\代码集合\\file-util\\src\\main\\resources\\files\\比较两个Excel文件的差异\\file1.xlsx");
        addWaterMark(workbook);
        OutputStream out = new FileOutputStream("C:\\Users\\zhoubin\\Desktop\\代码集合\\file-util\\src\\main\\resources\\files\\比较两个Excel文件的差异\\watermark2.xlsx");
        workbook.write(out);
    }

    public static void addWaterMark(XSSFWorkbook wb) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = createWaterMark("小烧杯");

        int pictureIdx = wb.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
        POIXMLDocumentPart poixmlDocumentPart = wb.getAllPictures().get(pictureIdx);
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            XSSFSheet xssfSheet = wb.getSheetAt(i);
            PackagePartName ppn = poixmlDocumentPart.getPackagePart().getPartName();
            String relType = XSSFRelation.IMAGES.getRelation();
            PackageRelationship pr = xssfSheet.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
            xssfSheet.getCTWorksheet().addNewPicture().setId(pr.getId());
            // 下面三行代码可设置表格内容不可复制、编辑
//            xssfSheet.protectSheet(UUID.randomUUID().toString());
//            xssfSheet.lockSelectUnlockedCells();
//            xssfSheet.lockSelectLockedCells();
        }
    }

    public static ByteArrayOutputStream createWaterMark(String content)
            throws IOException {
        int width = 200;
        int height = 150;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
        String fontType = "微软雅黑";
        int fontStyle = Font.BOLD;
        int fontSize = 20;
        Font font = new Font(fontType, fontStyle, fontSize);
        Graphics2D g2d = image.createGraphics(); // 获取Graphics2d对象
        image = g2d.getDeviceConfiguration().createCompatibleImage(width,
                height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        g2d.setColor(new Color(0, 0, 0, 20)); // 设置字体颜色和透明度，最后一个参数为透明度
        g2d.setStroke(new BasicStroke(1)); // 设置字体
        g2d.setFont(font); // 设置字体类型 加粗 大小
        g2d.rotate(-0.5, (double) image.getWidth() / 2,
                (double) image.getHeight() / 2);// 设置倾斜度
        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 写入水印文字原定高度过小，所以累计写水印，增加高度
        g2d.drawString(content, (int) x, (int) baseY);
        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return os;
    }
}
